package com.conwax.gmap;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.behavior.IBehavior;
import org.apache.wicket.markup.html.IHeaderResponse;

public class JsApiBehavior extends AbstractBehavior {

	private static final long serialVersionUID = 1L;

	// URL for Google Maps' API endpoint.
	private static final String GMAP_API_URL = "http://www.google.com/jsapi?key=";
	
	private final String jsApiKey;

	public JsApiBehavior(final String jsApiKey) {
		this.jsApiKey = jsApiKey;
	}

	@Override
	public void bind(Component component) {
		super.bind(component);
		if (!(component instanceof Page)) {
			throw new Error(this.getClass().getName()
					+ " may only be bound to a Page, not to a "
					+ component.toString());
		}
		for (IBehavior behavior : component.getBehaviors()) {
			if (behavior != this && behavior instanceof JsApiBehavior) {
				throw new Error("There may only be one "
						+ this.getClass().getName());
			}
		}
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		response.renderJavascriptReference(GMAP_API_URL + jsApiKey);
	}

}
